package com.elawlink.word;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import org.apache.poi.xwpf.converter.pdf.PdfConverter;
import org.apache.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import com.elawlink.util.DateUtil;
	
public class WordToPDF {
	/**
	 * 将word文档， 转换成pdf, 中间替换掉变量
	 * 
	 * @param source
	 *            源为word文档， 必须为docx文档
	 * @param target
	 *            目标输出
	 * @param params
	 *            需要替换的变量
	 * @throws Exception
	 */
	public static void wordConverterToPdf(InputStream source,
			OutputStream target, Map<String, String> params) throws Exception {
		wordConverterToPdf(source, target, null, params);
	}

	/**
	 * 将word文档， 转换成pdf, 中间替换掉变量
	 * 
	 * @param source
	 *            源为word文档， 必须为docx文档
	 * @param target
	 *            目标输出
	 * @param params
	 *            需要替换的变量
	 * @param options
	 *            PdfOptions.create().fontEncoding( "windows-1250" ) 或者其他
	 * @throws Exception
	 */
	public static void wordConverterToPdf(InputStream source, OutputStream target, PdfOptions options,
            Map<String, String> params) throws Exception {  
		XWPFDocument docx = new XWPFDocument(source);
	    PdfConverter.getInstance().convert(docx, target, options);  
    }
	
	
	public static void main(String[] args) {
		System.out.println("开始转换："+DateUtil.getSQLDate());
		
		String filepath = "E:\\mnt\\report\\template\\\\document_index.docx";
		String outpath = "E:\\mnt\\report\\template\\document_index.pdf";

		InputStream source;
		OutputStream target;
		try {
			source = new FileInputStream(filepath);
			target = new FileOutputStream(outpath);
			Map<String, String> params = new HashMap<String, String>();

			PdfOptions options = PdfOptions.create();

			wordConverterToPdf(source, target, options, params);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		System.out.println("结束转换："+DateUtil.getSQLDate());
	}
	
}

